package com.wanli.storemobile.login;


import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;
import com.wanli.storemobile.R;
import com.wanli.storemobile.a_main.MainActivity;
import com.wanli.storemobile.base.BaseActivity;
import com.wanli.storemobile.base.DataCallBack;
import com.wanli.storemobile.bean.ChannelTypeBean;
import com.wanli.storemobile.bean.LoginBean;
import com.wanli.storemobile.bean.UserInfoBean;
import com.wanli.storemobile.event.LoginRoleEvent;
import com.wanli.storemobile.homepage.MerchantIntoActivity;
import com.wanli.storemobile.homepage.StoreDataActivity;
import com.wanli.storemobile.homepage.model.HomePageModelImpl;
import com.wanli.storemobile.login.model.ILoginModel;
import com.wanli.storemobile.login.model.LoginModelImpl;
import com.wanli.storemobile.merchant.MerchantLoginActivity;
import com.wanli.storemobile.mine.UserAgreementActivity;
import com.wanli.storemobile.mine.model.MineModelImpl;
import com.wanli.storemobile.utils.SPManager;
import com.wanli.storemobile.utils.ToastUtil;
import com.wanli.storemobile.widget.ViewLoading;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.common.Constant;

import org.greenrobot.eventbus.Subscribe;

import java.util.List;
import java.util.Objects;

import androidx.annotation.NonNull;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LoginActivity extends BaseActivity {

    @BindView(R.id.edit_mobile)
    EditText editMobile;
    @BindView(R.id.edit_pwd)
    EditText editPwd;
    @BindView(R.id.cb_remember)
    CheckBox cbRemember;
    @BindView(R.id.tv_login)
    TextView tvLogin;
    @BindView(R.id.tv_forget_pwd)
    TextView tvForgetPwd;
    @BindView(R.id.tv_register_account)
    TextView tvRegisterAccount;
    @BindView(R.id.cb_display)
    CheckBox cbDisplay;
    @BindView(R.id.tv_merchant_self_registration)
    TextView tv_merchant_self_registration;
    @BindView(R.id.cbAgree)
    CheckBox cbAgree;
    @BindView(R.id.tv_pos_protocol)
    TextView tv_pos_protocol;
    @BindView(R.id.tv_privacy_policy)
    TextView tv_privacy_policy;
    private ILoginModel loginModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        registerEventBus();
        ImmersionBar.with(this)
                .statusBarDarkFont(true)
                .navigationBarDarkIcon(true)
                .navigationBarColor(R.color.white)
                .statusBarDarkFont(true, 0.2f)
                .init();
        initView();
        initEvent();
    }

    @Subscribe
    public void onLoginRoleEvent(LoginRoleEvent event) {
        finish();
    }

    public void initView() {
        loginModel = new LoginModelImpl();
        //点击眼隐藏或显示密码
        cbDisplay.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    //选择状态 显示明文--设置为可见的密码
                    editPwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    editPwd.setSelection(editPwd.getText().toString().length());
                } else {
                    //默认状态显示密码--设置文本 要一起写才能起作用 InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD
                    editPwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    editPwd.setSelection(editPwd.getText().toString().length());
                }
            }
        });
        String moblie = SPManager.getInstance().getUserMobile();
        String pwd = SPManager.getInstance().getUserPwd();
        if (!TextUtils.isEmpty(pwd)) {
            editMobile.setText(moblie);
            editMobile.setSelection(moblie.length());

            editPwd.setText(pwd);
            editPwd.setSelection(pwd.length());
            cbRemember.setChecked(true);
        }
    }
    public void initEvent() {
        tv_merchant_self_registration.setOnClickListener(v -> {
            //扫一扫
            scanCode();
        });
    }

    public void requesLogin() {
        String mobile = editMobile.getText().toString();
        String password = editPwd.getText().toString();
        if (TextUtils.isEmpty(mobile)) {
            ToastUtil.showShort("请输入手机号");
            return;
        }
        if (TextUtils.isEmpty(password)) {
            ToastUtil.showShort("请输入密码");
            return;
        }
        if (!cbAgree.isChecked()) {
            ToastUtil.showShort("请阅读并同意相关协议后登录");
            return;
        }
        ViewLoading.showProgress(mActivity, "登录中......");
        CloudPushService pushService = PushServiceFactory.getCloudPushService();
        loginModel.requestLoginByPwd(mobile, password, pushService.getDeviceId(), new DataCallBack<LoginBean>() {
            @Override
            public void onSuccessful(LoginBean bean) {
                SPManager.getInstance().saveRoleType("2");
                SPManager.getInstance().saveToken(bean.getData().getAccess_token());
                ToastUtil.showShort(bean.getMsg());
                requestUserInfo();
                SPManager.getInstance().saveUserMobile(mobile);
                if (cbRemember.isChecked()) {
                    SPManager.getInstance().saveUserPwd(password);
                } else {
                    SPManager.getInstance().saveUserPwd("");
                }
                showActivity(MainActivity.class);
                finish();
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    public void requestUserInfo() {
        new MineModelImpl().requestMine(new DataCallBack<UserInfoBean>() {
            @Override
            public void onSuccessful(UserInfoBean bean) {
                SPManager.getInstance().saveUserInfoJson(new Gson().toJson(bean));
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    @OnClick({R.id.tv_login, R.id.tv_forget_pwd, R.id.tv_register_account, R.id.tv_merchant_login, R.id.tv_pos_protocol, R.id.tv_privacy_policy})
    public void onViewClicked(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.tv_login:
                requesLogin();
                break;
            case R.id.tv_forget_pwd:
                showActivity(ForgetPwdActivity.class);
                break;
            case R.id.tv_register_account:
                showActivity(RegisterAccountActivity.class);
                break;
            case R.id.tv_merchant_login:
                showActivity(MerchantLoginActivity.class);
                break;
            case R.id.tv_pos_protocol:
                intent = new Intent(this, UserAgreementActivity.class);
                intent.putExtra("type", 1);
                startActivity(intent);
                break;
            case R.id.tv_privacy_policy:
                intent = new Intent(this, UserAgreementActivity.class);
                intent.putExtra("type", 2);
                startActivity(intent);
                break;
        }
    }


    private int REQUEST_CODE_SCAN = 111;//扫一扫请求状态码

    public void scanCode() {
        AndPermission.with(this)
                .runtime()
                .permission(Permission.CAMERA, Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE)
                .onGranted(new Action<List<String>>() {
                    @Override
                    public void onAction(List<String> permissions) {
                        Intent intent = new Intent(LoginActivity.this, CaptureActivity.class);
                        startActivityForResult(intent, REQUEST_CODE_SCAN);
                    }
                })
                .onDenied(new Action<List<String>>() {
                    @Override
                    public void onAction(@NonNull List<String> permissions) {
                        Uri packageURI = Uri.parse("package:" + Objects.requireNonNull(LoginActivity.this).getPackageName());
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                        Toast.makeText(LoginActivity.this, "没有权限无法扫描呦", Toast.LENGTH_LONG).show();
                    }
                })
                .start();
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 扫描二维码/条码回传
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {
                String qr_code_data = data.getStringExtra(Constant.CODED_CONTENT);
                Log.e("扫码返回结果",qr_code_data);
                if (qr_code_data.contains("agent_id")){
                    //获取服务商类型
                    getAgentType(qr_code_data);
                }else {
                    Toast.makeText(mActivity, "请扫描拓展二维码", Toast.LENGTH_SHORT).show();
                }

            }
        }
    }
    public void getAgentType(String qr_code_data) {
        new HomePageModelImpl().requestGetAgentType(qr_code_data, new DataCallBack<ChannelTypeBean>() {
            @Override
            public void onSuccessful(ChannelTypeBean bean) {

                if (bean.getData().getChannel_type() == 2) {
                    //智能版
                    Intent intent = new Intent(LoginActivity.this,StoreDataActivity.class);
                    intent.putExtra("qr_code_data",qr_code_data);
                    intent.putExtra("type", "1");
                    intent.putExtra("channel_type", "2");
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(LoginActivity.this, MerchantIntoActivity.class);
                    intent.putExtra("qr_code_data",qr_code_data);
                    intent.putExtra("channel_type", "1");
                    startActivity(intent);
                }
            }
            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }
}
